﻿using System;

namespace SelectionSort
{
    class SelectionSortAlgorithm
    {
        static void PrintArray(int[] array)
        {
            foreach (int number in array)
            {
                Console.Write("{0} ", number);
            }
            Console.WriteLine();
        }
        static int MaxNumber(int[] array, int startIndex, int endIndex)
        {
            int maxNumber = startIndex;
            for (int index = startIndex + 1, length = endIndex; index < length; index++)
            {
                if (array[index] > array[maxNumber])
                {
                    maxNumber = index;
                }
            }
            return maxNumber;
        }

        static void Swap(int[] array, int startIndex, int endIndex)
        {
            int tmp = array[startIndex];
            array[startIndex] = array[endIndex];
            array[endIndex] = tmp;
        }

        static void SelectionSort(int[] array, bool descending = true)
        {
            if (descending)
            {
                for (int index = array.Length - 1; index >= 0; index--)
                {
                    Swap(array, index, MaxNumber(array, 0, index + 1));
                }
            }
            else
            {
                for (int index = 0, length = array.Length; index < length; index++)
                {
                    Swap(array, index, MaxNumber(array, index, array.Length));
                }
            }
        }

        static void Main()
        {
            int[] array = { 3, 2, 8, 9, 1 };

            Console.WriteLine(array[MaxNumber(array, 0, array.Length)]);

            SelectionSort(array);
            PrintArray(array);

            SelectionSort(array, false);
            PrintArray(array);
        }
    }
}
